package com.gupaoedu.pattern.observer.event;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 2019/9/28
 * created by chenpp
 */
public class EventListener {

    private Map<String,Event> events = new HashMap<String,Event>();

    public void addListener(String eventType, Object target) throws Exception {
        //回调方法是on+eventType,参数是event
        if(target == null){
            throw new Exception("无法添加监听器");
        }
        this.addListener(eventType,target,target.getClass().getMethod("on"+toUpperFirstCharacter(eventType),Event.class));
    }

    public void addListener(String eventType, Object target, Method callback){
        events.put(eventType,new Event(target,callback));
    }

    //事件名称触发
    protected void trigger(String eventType){
        if(!this.events.containsKey(eventType)){
            return;
        }
        this.trigger(events.get(eventType).setEventName(eventType));
    }

    private void trigger(Event event){
        event.setSource(this);
        event.setTime(System.currentTimeMillis());

        try {
            if(event.getCallback() != null){
                event.getCallback().invoke(event.getTarget(),event);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    //首字母大写
    private String toUpperFirstCharacter(String str){
        char[] chars = str.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }

}
